/**
 * 
 */
package ar.com.greensoft.neo.model.constraint;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.springframework.util.StringUtils;

import ar.com.greensoft.neo.model.PersonaFisica;
import ar.com.greensoft.neo.model.references.Sexo;

/**
 * 
 * @author Jorge E. Villaverde
 * @since 23/01/2012
 * @version 1.0.0
 */
public class PersonaFisicaContraintsValidator implements ConstraintValidator<PersonaFisicaContraints, PersonaFisica> {
	private static final String PERSONA_FISICA_INVALID_CUIP_MESSAGE = "{ar.com.greensoft.neo.model.PersonaFisica.cuip.message}";
	private static final String PERSONA_FISICA_INVALID_CUIP_SEXO_MESSAGE = "{ar.com.greensoft.neo.model.PersonaFisica.cuip_sexo.message}";

	@Override
	public void initialize(PersonaFisicaContraints constraintAnnotation) {
	}

	@Override
	public boolean isValid(PersonaFisica value, ConstraintValidatorContext context) {
		boolean isValid = false;
		boolean cuipPersonaFisica = false;
		boolean cuipSexo = false;

		if(StringUtils.hasLength(value.getCuip())){
			String type = value.getCuip().substring(0, 2);
			Integer nType = 0;
			try{
				nType = Integer.parseInt(type);
				if((nType == 20 || nType == 23 || nType == 27)){
					cuipPersonaFisica = true;
					if(nType == 23){
						cuipSexo = true;
					}else{
						if(Sexo.HOMBRE.equals(value.getSexo()) && (nType == 20) ||
						   Sexo.MUJER.equals(value.getSexo())  && (nType == 27)){
							cuipSexo = true;						
						}
					}
				}
			}catch (NumberFormatException ne){
			}		
		}else{
			cuipSexo = true;
			cuipPersonaFisica = true;
		}
		
		isValid = cuipPersonaFisica && cuipSexo;
		
        if(!isValid) {
        	context.disableDefaultConstraintViolation();
        	
        	if(cuipPersonaFisica == false){
	        	context.buildConstraintViolationWithTemplate(
	        			PERSONA_FISICA_INVALID_CUIP_MESSAGE)
	        			.addNode("cuip")
	        			.addConstraintViolation();
        	}
        	if(cuipSexo == false){
	        	context.buildConstraintViolationWithTemplate(
	        			PERSONA_FISICA_INVALID_CUIP_SEXO_MESSAGE)
	        			.addNode("cuip")
	        			.addNode("sexo")
	        			.addConstraintViolation();
        	}        	
        }
				
        return isValid;
	}

}
